package cn.im.exception;

import cn.im.util.ResultVoUtil;
import cn.im.view.ResultVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;

import cn.im.tool.ErrCodeEnum;
import org.springframework.web.bind.annotation.ResponseStatus;

import java.util.Objects;

/**
 * @RestControllerAdvice  or  @ControllerAdvice结合@ExceptionHandler 全局异常的处理
 * 捕获异常的类，返回信息给请求方，可以自定义返回的code,msg等信息
 */
@ControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    /**
     * 通用异常
     * @return
     */
    @ExceptionHandler(Exception.class) //注解声明异常处理方法
    @ResponseStatus(HttpStatus.OK)
    public ResultVo handleException(Exception e){
    	log.error(e.getMessage(),e);
    	
    	if (e instanceof HttpMessageNotReadableException) {   //解析报文异常
            return  ResultVoUtil.error(ErrCodeEnum.EXCEPTION_REQUESTMSG_41001);
        }
        return  ResultVoUtil.error(ErrCodeEnum.EXCEPTION_UNKNOW);
    }

    /**
     * 自定义异常
     */
    @ExceptionHandler(value = CustomException.class)
    public ResultVo processException(CustomException e) {
        log.error("位置:{} -> 错误信息:{}", e.getMethod() ,e.getLocalizedMessage());
        return ResultVoUtil.error(Objects.requireNonNull(ErrCodeEnum.getByCode(e.getCode())));
    }

}